package com.envper.security.domain;

import com.envper.common.domain.dto.UserDto;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.io.Serial;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

@Slf4j
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
public class LoginUser implements UserDetails {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 用户ID
     */
    private Long userId;

    /**
     * 用户唯一标识
     */
    private String token;

    /**
     * 用户登录时间，单位毫秒
     */
    private Long loginTime;

    /**
     * 过期时间
     */
    private Long expiresAt;

    /**
     * 登录IP地址
     */
    private String ipAddr;

    /**
     * 登录地点
     */
    private String loginLocation;

    /**
     * 权限集合
     */
    private Set<String> permissions;

    /**
     * 认证列表
     */
    private List<SimpleGrantedAuthority> authorities;

    /**
     * 用户信息
     */
    private UserDto userDto;

    /**
     * 角色集合
     */
    private Set<String> roles;

    public LoginUser(Long userId, Set<String> permissions, Set<String> roles, UserDto userDto) {
        authorities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(roles)) {
            roles.forEach(i -> authorities.add(new SimpleGrantedAuthority(i)));
        }
        this.roles = roles;
        this.userId = userId;
        this.permissions = permissions;
        this.userDto = userDto;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return this.userDto.getPassword();
    }

    @Override
    public String getUsername() {
        if(ObjectUtils.isEmpty(userDto)) return null;
        return userDto.getUsername();
    }

    /**
     * 账号是否未过期，过期无法验证
     * @return true
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 指定用户是否解锁，锁定的用户无法进行身份验证
     * @return true
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 指示是否过期的用户的凭据（密码），过期的凭证防止认证
     * @return true
     */
    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 是否可用，禁用的用户不能身份验证
     * @return true
     */
    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return true;
    }
}
